import 'dart:async';
import 'dart:developer';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/pay/subscribe_entity.dart';
import 'package:ball_lion/module/expert/viewpoint/focus_bottomsheet.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:ball_lion/entity/expert/plan_Info_entity.dart';
import 'package:ball_lion/entity/other/resource_entity.dart';
import 'package:ball_lion/entity/pay/recharge_entity.dart';
import 'package:ball_lion/entity/pay/usable_coupon.dart';
import 'package:ball_lion/server/api/coupon_api.dart';
import 'package:ball_lion/server/api/expert_api.dart';
import 'package:ball_lion/server/api/pay_api.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/expert/expert_info_view.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';
import 'package:ball_lion/module/pay/pay_bottom_sheet.dart';

class ViewpointLogic extends GetxController {
  bool get focus => (planInfo?.isFocus ?? 0) > 0;
  bool get matchStart =>
      (planInfo?.matchTime?.difference(DateTime.now()).inSeconds ?? 1) < 0;
  bool get readable => planInfo?.canRead ?? false;
  bool get isCanPay => planInfo?.canPay ?? false;
  bool barShow = false;
  double topOffset = 115;
  bool _focusMatch = true;
  List<UsableCouponEntity>? coupons;
  List<SubscribleCardEntity>? subCards;

  final refreshController = EasyRefreshController(controlFinishRefresh: true);
  final ScrollController refreshScroll = ApmScrollController();
  late int? planId = Get.arguments ?? 0;
  PlanInfoEntity? planInfo;
  late QsPlayerLogic videoLogic;
  Timer? t;
  List<ResourceEntity> viewpointTips = [];
  int? roomId = Get.parameters['roomId'].toInt();
  late ExpertInfoView expertView = ExpertInfoView(
      planInfo: planInfo, toFocus: clickToFocus, toDetail: clickToExpert);

  bool get focusMatch => _focusMatch;

  set focusMatch(bool value) {
    _focusMatch = value;
    update();
  }

  @override
  onInit() {
    videoLogic = Get.put(QsPlayerLogic(autoPlay: false), tag: "${planId ?? 0}");
    refreshScroll.addListener(() {
      if (refreshScroll.offset > 70 && barShow == false) {
        barShow = true;
        update();
      }
      if (refreshScroll.offset < 70 && barShow == true) {
        barShow = false;
        update();
      }
    });
    doRequestData();
    Utils.onEvent('fa_cx',
        params: {'fa_cx': planInfo?.sportsId == 1 ? "足球" : "篮球"});
    if (!matchStart) {
      t = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (matchStart) {
          Future.delayed(const Duration(seconds: 1)).then((value) {
            doRequestData();
          });
          timer.cancel();
        }
        // update();
      });
    }
    super.onInit();
  }

  @override
  void dispose() {
    t?.cancel();
    super.dispose();
  }

  requestCoupons() async {
    if (planInfo == null || !User.isLogin) {
      return;
    }
    double gold = double.parse(planInfo!.priceReal!);
    final getCoupons = await CouponApi.use1Coupons(
        gold: gold, otherId: planInfo?.expertId ?? "", scene: PayScene.expert);
    coupons = getCoupons ?? coupons;
    update();
  }

  doRequestData() async {
    if (planId == null) {
      return;
    }
    planInfo = await ExpertApi.getPlanInfo(planId!);
    if (!(planInfo?.planId.hasValue ?? false)) {
      update();
      return;
    }
    // log("get plan inf = ${data.toJson()}");
    expertView = ExpertInfoView(
        planInfo: planInfo, toFocus: clickToFocus, toDetail: clickToExpert);
    requestCoupons();
    log("=============结束");
    update();
  }

  clickToFocus() async => await User.needLogin(() async {
        final id = planInfo?.expertId;
        if (id == null) {
          return;
        }
        if (focus) {
          final result = await WidgetUtils.alertQuery('确认不再关注？');
          if (result == true) {
            Utils.onEvent('gdxq_gz', params: {'gdxq_gz': '0'});
            if (await UserApi.unFocus(expertId: id) == 200) {
              Toast.text("取消关注成功");
            } else {
              Toast.text("取消关注失败");
            }
          }
        } else {
          Utils.onEvent('gdxq_gz', params: {'gdxq_gz': '1'});
          if (await UserApi.focus(expertId: id) == 200) {
            Toast.text("关注成功");
          } else {
            Toast.text("关注失败");
          }
        }
        await doRequestData();
      });

  clickToPay() async {
    // if(roomId != null){
    //   Utils.onEvent('liveroom_plan_pay', params: {"plan_id": planInfo?.planId?? -1});
    // } else {
    Utils.onEvent('plan_detail_pay', params: {
      "plan_id": planInfo?.planId ?? 0,
      'param2': roomId == null ? '0' : '1'
    });
    // }
    if (!isCanPay) {
      Toast.text(planInfo?.footerContent ?? "方案所含比赛已开始，当前不可付费阅读！");
      return;
    }
    bool ulogin = User.isLogin;
    User.needLogin(() async {
      if (!ulogin) {
        await doRequestData();
      }
      if (planInfo?.isFocus == 0 && planInfo?.activityId == 2) {
        bool toPay =
            await Get.bottomSheet(FocusBottomSheet(planInfo: planInfo));
        if (toPay) doPayAction();
      } else {
        doPayAction();
      }
    });
  }

  clickToExpert() async {
    Utils.onEvent('gdxq_zjtx');
    final expertId = planInfo?.expertId;
    if (expertId?.isEmpty ?? true) {
      return;
    }
    Get.toNamed(Routes.userPage, arguments: expertId!, parameters: {
      'type': '2',
      "index": planInfo?.sportsId == 1 ? "zq" : "lq"
    });
  }

  doPayAction() async {
    final price = planInfo?.priceReal;
    if (price == null) {
      return;
    }
    final gold = double.tryParse(price);
    if (gold == null) {
      return;
    }
    final PayResult? result = await Get.bottomSheet(
        isScrollControlled: true,
        PayBottomSheet(
            payInfo: PayInfo(
                price: price,
                payScene: PayScene.expert,
                buyId: "$planId",
                ownerId: planInfo?.expertId,
                coupons: coupons)));
    if (result != null && result.toPay == PayStatus.goldPay) {
      log("--------goldPay--------");
      var s = await PayApi.planOrder(gold, "$planId",
          couponGold: result.coupon?.gold,
          couponId: result.coupon?.id == null ? null : "${result.coupon?.id}",
          subsId: result.subcard?.id == null ? null : "${result.subcard?.id}",
          roomId: roomId);
      if (s == true) {
        // if(roomId != null){
        //   Utils.onEvent('liveroom_plan_pay_done');
        // } else {
        Utils.onEvent('pay_done');
        // }
        doFocusMatch();
        await doRequestData();
      } else {
        Utils.onEvent('gdxq_zfyd_qxzf');
      }
    } else if (result?.toPay == PayStatus.directPay) {
      log("--------directPay--------");
      Utils.onEvent('gdxq_zfyd_qrzf');
      doFocusMatch();
      await doRequestData();
    } else {
      Utils.onEvent('gdxq_zfyd_qxzf');
    }
    User.fetchUserInfo(fetchFocus: false);
  }

  Future doVipPay() async {
    if (User.info?.isVip != 1) {
      return Get.toNamed(Routes.vipCenter);
    }
    bool result = await Get.dialog(QsDialog.alert("会员每天可解锁1篇方案，确认解锁该方案吗？"));
    if (result) {
      var r = await PayApi.vipPlanPay("$planId").then((value) {
        doFocusMatch();
        doRequestData();
      });
      if (r == false) {
        Get.dialog(QsDialog.single("会员每天可免费解锁1篇方案，今日解锁已达上限。"));
      }
    }
  }

  Future doFocusMatch() async {
    if (focusMatch) {
      List<int> ids =
          planInfo?.matchBries?.map((e) => e.matchId ?? 0).toList() ?? [];
      if (planInfo?.sportsId == 1) {
        await UserApi.makeMatchFocusUpdate(ids, true);
      } else {
        await UserApi.makeBasketballMatchFocusUpdate(ids, true);
      }
      User.fetchUserInfo();
    }
  }
}
